package cn.bornsoft.mobileServer.servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.bornsoft.utils.ImageControl;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 处理图片，进行自动缩略
 * 
 * @author JONES
 * 
 */
public class ImageGen extends HttpServlet {
	static Logger log = Logger.getLogger(ImageGen.class);

	/**
	 * Constructor of the object.
	 */
	public ImageGen() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String p = request.getParameter("p");
		String w = request.getParameter("w");
		String h = request.getParameter("h");
		int w1 = Integer.parseInt(w == null || "".equals(w) ? "0" : w);
		int h1 = Integer.parseInt(h == null || "".equals(h) ? "0" : h);
		ImageControl ic = new ImageControl();
		BufferedImage d = ic.loadImageUrl(p);
		d = ic.resize(d, w1);
		ServletOutputStream out = response.getOutputStream();
		// 发送图片数据
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(d);
		param.setQuality(1, true);// 质量要<=1
		encoder.setJPEGEncodeParam(param);
		encoder.encode(d);
		log.debug("resize image:" + p);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
